package com.tenglong.teacher.ui.adapter.viewholder;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Typeface;
import android.support.v4.content.ContextCompat;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.text.style.StyleSpan;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.Priority;
import com.bumptech.glide.load.DecodeFormat;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.cuotibao.zhuoxiao.basics.GlobalConstant;
import com.cuotibao.zhuoxiao.basics.utils.DensityUtil;
import com.cuotibao.zhuoxiao.basics.utils.glide.GlideOptions;
import com.netease.nim.uikit.common.util.sys.TimeUtil;
import com.netease.nimlib.sdk.msg.constant.MsgDirectionEnum;
import com.tenglong.teacher.R;
import com.tenglong.teacher.data.resultInfo.HomeDetailInfo;
import com.tenglong.teacher.ui.PhotoBrowserActivity;
import com.tenglong.teacher.ui.adapter.viewholder.base.BaseViewHolder;
import com.tenglong.teacher.ui.audio.MediaManager;

import java.util.ArrayList;
import java.util.List;

import static com.tenglong.teacher.ui.adapter.HomeworkListAdapter.isCheck;

/**
 * @author hdx on 2019/5/21.
 */
public class HomeworkListViewHolder extends BaseViewHolder<HomeDetailInfo> implements View.OnClickListener {
    private TextView title;
    private ViewGroup errorList;
    private String placeholder = "&/";
    private TextView homeworkComment;
    private ViewGroup imageList;
    private TextView tvHomeworkAudio;
    private ViewGroup homeworkAudio;
    private ImageView ivHomeworkAudio;
    private ImageView img;
    private HomeDetailInfo data;
    private HomeworkListViewHolder.OnViewHideListener listener;
    private int listSzie=0;
    public HomeworkListViewHolder(View itemView,int listSzie,HomeworkListViewHolder.OnViewHideListener listener) {
        super(itemView);
        this.listSzie=listSzie;
        this.listener=listener;
        initView();
        setListeners();
    }

    private void setListeners() {
        homeworkAudio.setOnClickListener(this);
    }

    private void initView() {
        title = itemView.findViewById(R.id.title);
        errorList = itemView.findViewById(R.id.errorList);
        homeworkComment = itemView.findViewById(R.id.homeworkComment);
        imageList = itemView.findViewById(R.id.imageList);

        homeworkAudio = itemView.findViewById(R.id.homeworkAudio);
        ivHomeworkAudio = itemView.findViewById(R.id.iv_homeworkAudio);
        tvHomeworkAudio = itemView.findViewById(R.id.tv_homeworkAudio);
        img= itemView.findViewById(R.id.img);
    }

    @Override
    public void setLayoutInfo(HomeDetailInfo info) {
        this.data = info;
        if (info.direct == MsgDirectionEnum.Out) {
            title.setText("老师批改");
            title.setCompoundDrawablesWithIntrinsicBounds(R.drawable.pigai, 0, 0, 0);
        } else {
            title.setText("学生提交");
            title.setCompoundDrawablesWithIntrinsicBounds(R.drawable.tijiao, 0, 0, 0);
        }
        if(listSzie>3 && getLayoutPosition()==1){
            img.setVisibility(View.VISIBLE);
        }else{
            img.setVisibility(View.GONE);
        }
        img.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(isCheck){
                    img.setImageResource(R.mipmap.jiantou_shou);
                }else{
                    img.setImageResource(R.mipmap.jiantou_xia);
                }
                listener.onViewHideClick(isCheck);
                isCheck=!isCheck;
            }
        });
        homeworkAudio.setVisibility(TextUtils.isEmpty(info.audioUrl) || info.audioDuration == 0 ? View.GONE : View.VISIBLE);
        if (homeworkAudio.getVisibility() == View.VISIBLE) {
            long seconds = TimeUtil.getSecondsByMilliseconds(info.audioDuration);
            if (seconds >= 0) {
                tvHomeworkAudio.setText(seconds + "\"");
            } else {
                tvHomeworkAudio.setText("");
            }
        }

        homeworkComment.setVisibility(TextUtils.isEmpty(info.evaluate) ? View.GONE : View.VISIBLE);
        if (homeworkComment.getVisibility() == View.VISIBLE) {
            SpannableStringBuilder text = getDisplayText(info.evaluate, homeworkComment);
            homeworkComment.setText(text);
        }

        errorList.setVisibility(info.errorContents == null || info.errorContents.size() == 0 ? View.GONE : View.VISIBLE);
        errorList.removeAllViews();
        if (errorList.getVisibility() == View.VISIBLE) {
            for (String error : info.errorContents) {
                TextView textView = new TextView(mContext);
                SpannableStringBuilder text = getDisplayText(error, textView);
                textView.setLineSpacing(DensityUtil.dp2px(3), 1);
                textView.setText(text);
                errorList.addView(textView);
            }
        }

        imageList.setVisibility(info.imageUrls == null || info.imageUrls.size() == 0 ? View.GONE : View.VISIBLE);
        imageList.removeAllViews();
        if (imageList.getVisibility() == View.VISIBLE) {
            for (int i = 0; i < info.imageUrls.size(); i++) {
                if (((i + 1) % 3) == 1) {
                    LinearLayout linear = new LinearLayout(mContext);
                    imageList.addView(linear);
                    ViewGroup.LayoutParams params = linear.getLayoutParams();
                    params.width = ViewGroup.LayoutParams.MATCH_PARENT;
                    params.height = DensityUtil.dp2px(83);
                    if (params instanceof ViewGroup.MarginLayoutParams && imageList.getChildCount() != 1) {
                        ((ViewGroup.MarginLayoutParams) params).topMargin = DensityUtil.dp2px((float) 20.25);
                    }
                    linear.setLayoutParams(params);
                }
            }
            for (int i = 0; i < info.imageUrls.size(); i++) {
                ImageView imageView = new ImageView(mContext);
                ((ViewGroup) imageList.getChildAt(i / 3)).addView(imageView);
                ViewGroup.LayoutParams layoutParams = imageView.getLayoutParams();
                layoutParams.height = DensityUtil.dp2px(83);
                layoutParams.width = DensityUtil.dp2px(83);
                if (layoutParams instanceof ViewGroup.MarginLayoutParams) {
                    ViewGroup.MarginLayoutParams marginLayoutParams = (ViewGroup.MarginLayoutParams) layoutParams;
                    marginLayoutParams.leftMargin = DensityUtil.dp2px((float) 20.25);
                }
                imageView.setLayoutParams(layoutParams);
                RequestOptions options = GlideOptions.getGlideRequestOptions()
                        .placeholder(com.netease.nim.uikit.R.drawable.nim_image_default)
                        .error(com.netease.nim.uikit.R.drawable.nim_image_default);
                Glide.with(mContext)
                        .load(info.imageUrls.get(i))
                        .apply(options)
                        .into(imageView);
                imageView.setId(i);
                imageView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent i = new Intent();
                        i.setClass(mContext, PhotoBrowserActivity.class);
                        i.putExtra(GlobalConstant.KEY_IMAGE_URLS, data.imageUrls.toArray(new String[data.imageUrls.size()]));
                        i.putExtra(GlobalConstant.KEY_CURRENT_IMAGE_URL, data.imageUrls.get(v.getId()));
                        mContext.startActivity(i);
                        ((Activity) mContext).overridePendingTransition(0, 0);
                    }
                });
            }
        }

    }


    protected SpannableStringBuilder getDisplayText(String str, TextView textView) {
        if (TextUtils.isEmpty(str)) {
            return null;
        }
        String text = str.replace("\\n", "\n");
        List<PositionPoint> list = new ArrayList<>();
        boolean isStrat = true;
        int p = 0;
        while (isStrat) {
            int index = text.indexOf(placeholder, p);
            if (index != -1) {
                list.add(new PositionPoint(index, p = index + 4));
            } else {
                isStrat = false;
                p = 0;
            }
        }
        SpannableStringBuilder builder = new SpannableStringBuilder(text.replace(placeholder, "错误"));
        if (text.contains("错题原因：") || text.contains("作业点评：") || text.contains("书写评分：") || text.contains("老师批语：")
                || text.contains("错题原因:") || text.contains("作业点评:") || text.contains("书写评分:") || text.contains("老师批语:")) {
            if ((text.contains("错题原因：") || text.contains("错题原因:")) && !text.contains("作业点评：") && !text.contains("书写评分：") && !text.contains("老师批语：")
                    && !text.contains("作业点评:") && !text.contains("书写评分:") && !text.contains("老师批语:")) {
                textView.setTextColor(ContextCompat.getColor(mContext, R.color.mygreydark));
            } else {
                textView.setTextColor(ContextCompat.getColor(mContext, R.color.app_red));
                if (text.contains("老师批语：") || text.contains("老师批语:")) {
                    int i = 0;
                    if (text.contains("老师批语：")) {
                        i = text.indexOf("老师批语：");
                    } else if (text.contains("老师批语:")) {
                        i = text.indexOf("老师批语:");
                    }
                    if (i != 0) {
                        builder.setSpan(new ForegroundColorSpan(ContextCompat.getColor(mContext, R.color.mygreydark)), i + 5, text.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                    }
                }
            }
            for (PositionPoint positionPoint : list) {
                builder.setSpan(new ForegroundColorSpan(ContextCompat.getColor(mContext, R.color.app_red)), positionPoint.startPoint, positionPoint.stopPoint, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            }
            return getStringBuilder(builder, text, new String[]{"错题原因：", "作业点评：", "书写评分：", "老师批语：", "错题原因:", "作业点评:", "书写评分:", "老师批语:"});
        } else {
            textView.setTextColor(ContextCompat.getColor(mContext, R.color.mygreydark));
            return builder;
        }
    }

    private SpannableStringBuilder getStringBuilder(SpannableStringBuilder builder, String text, String[] tips) {
        for (String str : tips) {
            if (text.contains(str)) {
                int p = text.indexOf(str);
                builder.setSpan(new ForegroundColorSpan(ContextCompat.getColor(mContext, R.color.black)), p, p + 5, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                builder.setSpan(new StyleSpan(Typeface.BOLD), p, p + 5, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            }
        }
        return builder;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.homeworkAudio:
                if (!TextUtils.isEmpty(data.audioUrl)) {
                    MediaManager.release();
//                    final AnimationDrawable drawable = ((AnimationDrawable) ivHomeworkAudio.getBackground());
//                    MediaManager.playSound(data.homeworkAudioUrl, new MediaPlayer.OnCompletionListener() {
//                        @Override
//                        public void onCompletion(MediaPlayer mp) {
//                            drawable.selectDrawable(3);
//                            MediaManager.stop();
//                            MediaManager.release();
//                            drawable.stop();
//                        }
//                    }, new MediaPlayer.OnErrorListener() {
//                        @Override
//                        public boolean onError(MediaPlayer mp, int what, int extra) {
//                            drawable.selectDrawable(3);
//                            MediaManager.stop();
//                            MediaManager.release();
//                            drawable.stop();
//                            return false;
//                        }
//                    }, new MediaPlayer.OnPreparedListener() {
//                        @Override
//                        public void onPrepared(MediaPlayer mp) {
//                            MediaManager.play();
//                            drawable.start();
//                        }
//                    });
//                }
                    MediaManager.playSound(data.audioUrl, null);
                }
                break;
        }
    }

    class PositionPoint {
        int startPoint;
        int stopPoint;

        PositionPoint(int startPoint, int stopPoint) {
            this.startPoint = startPoint;
            this.stopPoint = stopPoint;
        }
    }
    public interface OnViewHideListener{
        void onViewHideClick(boolean isCheck);
    }
}
